/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.minhphuong.dal;

import com.minhphuong.entities.*;
import java.net.PasswordAuthentication;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.ui.ModelMap;
import java.util.Properties;

/**
 *
 * @author QuocMinh
 */
public class SanPhamDAL {

    public static List<SanPham> getAllSanPham() {
        List<SanPham> listSanPham = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from SanPham");
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            for (SanPham sanpham : listSanPham) {
                Hibernate.initialize(sanpham.getHang());
            }
            //Hibernate.initialize(sanPham.getHang());
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> get6SanPhamNewest() {
        List<SanPham> listSanPham = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from SanPham order by MaSp desc").setMaxResults(6);
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            for (SanPham sanpham : listSanPham) {
                Hibernate.initialize(sanpham.getHang());
            }
            //Hibernate.initialize(sanPham.getHang());
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> get6SanPhamHot() {
        List<SanPham> listSanPham = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from SanPham").setMaxResults(6);
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            for (SanPham sanpham : listSanPham) {
                Hibernate.initialize(sanpham.getHang());
            }
            //Hibernate.initialize(sanPham.getHang());
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static SanPham getSanPhamByID(int id) {
        SanPham sanPham = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from SanPham where MaSp=:id").setInteger("id", id);
            sanPham = (SanPham) q.list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sanPham != null) {
                for (MauSanPham mau : sanPham.getMauSanPhams()) {
                    Hibernate.initialize(mau.getMau());
                }
                Hibernate.initialize(sanPham.getHang());
                Hibernate.initialize(sanPham.getChiTietSanPham());
            }
            session.flush();
            session.close();
        }

        return sanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> getTopSanPham(int n) {
        List<SanPham> listSanPham = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery("from SanPham");
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static Hang getAllSanPhamByHang(String tenHang) {
        Hang hang = null;
        Session session = null;

        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            String query = "from Hang where tenHang=\"" + tenHang + "\"";
            Query q = session.createQuery(query);
            if (q.list().size() > 0) {
                hang = ((Hang) q.list().get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (hang != null) {
                Hibernate.initialize(hang.getSanPhams());
                Hibernate.initialize(hang.getSanPhams().size());
            }
            session.flush();
            session.close();
        }

        return hang;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static boolean insertSanPham(SanPham sanpham) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HelperDAL.GetSession();
            tx = session.beginTransaction();
            session.save(sanpham);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            session.flush();
            session.close();
        }
        return true;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> getAllSanPhamByTimKiem(String search_category, String search_price, String search_productname) {
        List<SanPham> listSanPham = null;
        Session session = null;
        int so1 = 0, so2 = 0;
        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            String query = "from SanPham sp where 1=1";

            if (Integer.parseInt(search_category) != 0) {
                query += " and sp.hang.maH=" + search_category;
            }

            if (search_productname != "") {
                query += " and sp.tenSanPham like \"%" + search_productname + "%\"";
            }

            if (Integer.parseInt(search_price) != 0) {
                switch (Integer.parseInt(search_price)) {
                    case 1:
                        so1 = 0;
                        so2 = 999999;
                        break;
                    case 2:
                        so1 = 1000000;
                        so2 = 2999999;
                        break;
                    case 3:
                        so1 = 3000000;
                        so2 = 4999999;
                        break;
                    case 4:
                        so1 = 5000000;
                        so2 = 7999999;
                        break;
                    case 5:
                        so1 = 8000000;
                        so2 = 11999999;
                        break;
                    case 6:
                        so1 = 12000000;
                        so2 = 19999999;
                        break;
                    case 7:
                        so1 = 20000000;
                        so2 = 99999999;
                        break;
                }
                query += " and sp.donGia between " + so1 + " and " + so2;
            }

            Query q = session.createQuery(query);
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            for (SanPham sanPham : listSanPham) {
                Hibernate.initialize(sanPham.getHang().getTenHang());
            }
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> getAllSanPhamByTimKiemLimit(String search_category, String search_price, String search_productname, int start, int display) {
        List<SanPham> listSanPham = null;
        Session session = null;
        int so1 = 0, so2 = 0;
        try {
            session = HelperDAL.GetSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            String query = "from SanPham sp where 1=1";

            if (Integer.parseInt(search_category) != 0) {
                query += " and sp.hang.maH=" + search_category;
            }

            if (search_productname != "") {
                query += " and sp.tenSanPham like \"%" + search_productname + "%\"";
            }

            if (Integer.parseInt(search_price) != 0) {
                switch (Integer.parseInt(search_price)) {
                    case 1:
                        so1 = 0;
                        so2 = 999999;
                        break;
                    case 2:
                        so1 = 1000000;
                        so2 = 2999999;
                        break;
                    case 3:
                        so1 = 3000000;
                        so2 = 4999999;
                        break;
                    case 4:
                        so1 = 5000000;
                        so2 = 7999999;
                        break;
                    case 5:
                        so1 = 8000000;
                        so2 = 11999999;
                        break;
                    case 6:
                        so1 = 12000000;
                        so2 = 19999999;
                        break;
                    case 7:
                        so1 = 20000000;
                        so2 = 99999999;
                        break;
                }
                query += " and sp.donGia between " + so1 + " and " + so2;
            }

            Query q = session.createQuery(query);
            q.setFirstResult(start);
            q.setMaxResults(display);
            listSanPham = (List<SanPham>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            for (SanPham sanPham : listSanPham) {
                Hibernate.initialize(sanPham.getHang().getTenHang());
            }
            session.flush();
            session.close();
        }

        return listSanPham;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static List<SanPham> getAllSanPhamGioHang(HttpSession session) {
        List<SanPham> listSanPham = SanPhamDAL.getAllSanPham();
        List<SanPham> listSanphamGioHang = SanPhamDAL.getAllSanPham();
        listSanphamGioHang.clear();

        for (SanPham sanPham : listSanPham) {
            if (session.getAttribute("" + sanPham.getMaSp()) != null) {
                sanPham.setSoLuong((Integer) session.getAttribute("" + sanPham.getMaSp()));
                listSanphamGioHang.add(sanPham);
            }
        }

        return listSanphamGioHang;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static void deleteAllSanPhamGioHang(HttpSession session) {
        List<SanPham> listSanPham = SanPhamDAL.getAllSanPham();

        for (SanPham sanPham : listSanPham) {
            if (session.getAttribute("" + sanPham.getMaSp()) != null) {
                session.removeAttribute("" + sanPham.getMaSp());
            }
        }
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static void deleteSanPhamGioHangByID(HttpSession session, int id) {
        if (session.getAttribute("" + id) != null) {
            session.removeAttribute("" + id);
        }
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static void updateGioHang(HttpSession session, HttpServletRequest request) {
        List<SanPham> listSanPham = SanPhamDAL.getAllSanPham();

        for (SanPham sanPham : listSanPham) {
            // nếu là sp trong giỏ hàng thì cập nhật
            if (session.getAttribute("" + sanPham.getMaSp()) != null) {
                // kiểm tra coi có đủ số lượng không mới cập nhật
                if (Integer.parseInt(request.getParameter("" + sanPham.getMaSp())) <= (sanPham.getSoLuongTon() - sanPham.getSoLuongDangMua())) {
                    session.setAttribute("" + sanPham.getMaSp(), Integer.parseInt(request.getParameter("" + sanPham.getMaSp())));
                    // cập nhật xong mà = 0, thì xóa nó luôn
                    if ((Integer) session.getAttribute("" + sanPham.getMaSp()) == 0) {
                        session.removeAttribute("" + sanPham.getMaSp());
                    }
                }
            }
        }
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public static void submitGioHangHoaDon(HttpSession session, HttpServletRequest request, ModelMap map) {
        List<SanPham> listSanPham = SanPhamDAL.getAllSanPham();

        String error_submit_str = "Xin lỗi bạn\\n\\n";
        int error_submit = 0;

        for (SanPham sanPham : listSanPham) {
            // nếu là sp trong giỏ hàng thì cập nhật
            if (session.getAttribute("" + sanPham.getMaSp()) != null) {
                // kiểm tra coi có đủ số lượng không mới cập nhật
                if ((Integer)session.getAttribute("" + sanPham.getMaSp()) > (sanPham.getSoLuongTon() - sanPham.getSoLuongDangMua())) {
                    error_submit = 1;
                    int inventory = sanPham.getSoLuongTon() - sanPham.getSoLuongDangMua();
                    if (inventory == 0) {
                        error_submit_str += "Sản phẩm " + sanPham.getTenSanPham() + " đã hết!\\n";
                    } else {
                        error_submit_str += "Sản phẩm " + sanPham.getTenSanPham() + " chỉ còn " + inventory + " cái! \\n";
                    }

                    session.setAttribute("" + sanPham.getMaSp(), Integer.parseInt(request.getParameter("" + sanPham.getMaSp())));
                    // cập nhật xong mà = 0, thì xóa nó luôn
                    if ((Integer) session.getAttribute("" + sanPham.getMaSp()) == 0) {
                        session.removeAttribute("" + sanPham.getMaSp());
                    }
                }
            }
        }

        map.addAttribute("error_submit", error_submit);
        map.addAttribute("error_submit_str", error_submit_str);

        if (error_submit == 0) {
            // tạo hóa đơn
            String order_code = request.getParameter("order_code");
            String order_date = request.getParameter("order_date");

            String order_name = request.getParameter("order_name");
            String order_phone = request.getParameter("order_phone");
            String order_email = request.getParameter("order_email");
            String order_address = request.getParameter("order_address");
            String phuongthucthanhtoan = request.getParameter("phuongthucthanhtoan");
            String order_note = request.getParameter("order_note");
            String order_total = request.getParameter("order_total");

            HoaDon hoaDon = new HoaDon();
            hoaDon.setCachThanhToan(Integer.parseInt(phuongthucthanhtoan));
            hoaDon.setCodeHoaDon(order_code);
            hoaDon.setDiaChi(order_address);
            hoaDon.setEmail(order_email);
            hoaDon.setGhiChu(order_note);
            hoaDon.setMaHd(HelperDAL.getNextID("HoaDon", "maHd"));
            hoaDon.setNgayDatHang(new Timestamp(Long.parseLong(order_date)));
            hoaDon.setNguoiDungByMaNd(NguoiDungDAL.checkSession(session));
            hoaDon.setSoDienThoai(order_phone);
            hoaDon.setTongTriGia(Integer.parseInt(order_total));
            hoaDon.setTenNguoiNhan(order_name);
            hoaDon.setTrangThaiHoaDon(TrangThaiHoaDonDAL.getTrangThaiHoaDonByID(1));

            HoaDonDAL.insertHoaDon(hoaDon);

            KhuyenMai khuyenMai = KhuyenMaiDAL.getKhuyenMai();
            boolean promotion_start = Boolean.parseBoolean(request.getParameter("promotion_start"));

            // tạo chi tiết hóa đơn
            for (SanPham sanPham : listSanPham) {
                // nếu là sp trong giỏ hàng thì insert
                if (session.getAttribute("" + sanPham.getMaSp()) != null) {
                    int price_real = 0;
                    if (promotion_start == true) {
                        price_real = (Integer) sanPham.getDonGia() * (100 - khuyenMai.getPhanTram()) / 100;
                    } else {
                        price_real = (Integer) sanPham.getDonGia();
                    }
                    ChiTietHoaDon cthd = new ChiTietHoaDon();
                    cthd.setDonGia(price_real);
                    cthd.setHoaDon(hoaDon);
                    cthd.setMaCthd(HelperDAL.getNextID("ChiTietHoaDon", "maCthd"));
                    cthd.setSanPham(sanPham);
                    cthd.setSoLuong((Integer) session.getAttribute("" + sanPham.getMaSp()));
                    ChiTietHoaDonDAL.insertCTHD(cthd);

                    sanPham.setSoLuongDangMua(sanPham.getSoLuongDangMua() + (Integer) session.getAttribute("" + sanPham.getMaSp()));
                    SanPhamDAL.updateSanPham(sanPham);
                }
            }
        }
        // delete giỏ hàng
        SanPhamDAL.deleteAllSanPhamGioHang(session);
    }

    public static void updateSanPham(SanPham sanPham) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HelperDAL.GetSession();
            tx = session.beginTransaction();
            session.update(sanPham);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
